var aypId = "";
var url = "";
var postbox = new ko.subscribable();
//var displayMode = ko.observable(true);
var editMode = true;
var editEventHolidayOnly = ko.observable(false);
// Can Edit Only Events And Holidays if 'true'
// true - enable to save n edit
var noOfWorkingDays = 0;
//false - view mode only
var isHelpActive = false;
var academicYearStartDate;
var academicYearEndDate;
var academicYearPlanTitle;
var holidayStartDate;
var holidayEndDate;

var createAcademicYearModel = function() {

	//var self:this;

	var self = this;
	//self.title = ko.observable("").extend({ required: { message: 'Please supply your email address.' },minLength: {params:2,message:'min length required'}});
	self.title = ko.observable("").extend({
		required : true
	});
	self.aypId = ko.observable(aypId);
	self.startDate = ko.observable("").extend({
		required : true
	});
	self.endDate = ko.observable("").extend({
		required : true
	});
	;

	self.planStatus = ko.observable(0);
	self.holidays = ko.observableArray();

	self.startDate.subscribe(function(value) {
		console.log("startDate:", value);
		academicYearStartDate = value;
		if (!isEventsDataLoaded) {
			isEventsDataLoaded = true;
			getSchoolAcademicEvents("getOnlyData");
		} else {
			if (!byCode) {
				self.checkForValidity("startDate")
			}
		}

		jQuery(".datepicker_ayp_end").datepicker("option", "minDate", academicYearStartDate);
		jQuery(".datepicker_ayp_start").datepicker("option", "minDate", academicYearStartDate);

		jQuery("#academicYearEnd").datepicker("option", "minDate", self.startDate());

		// jQuery(".datepicker_ayp").datepicker({beforeShowDay : function(date){
		// console.log("beforeShowDay  ### datepicker_ayp_start", date)
		// }});
		jQuery(".datepicker_ayp").datepicker("option", "minDate", academicYearStartDate);
		jQuery(".datepicker_ayp").datepicker("option", "maxDate", academicYearEndDate);

		//set previous date here
		self.startDate.previousDate = self.startDate();

	});

	self.endDate.subscribe(function(value) {
		console.log("endDate:", value);
		academicYearEndDate = value;

		if (!isEventsDataLoaded) {
			isEventsDataLoaded = true;
			getSchoolAcademicEvents("getOnlyData");
		} else {
			if (!byCode) {
				self.checkForValidity("endDate")
			}
		}
		jQuery("#academicYearStart").datepicker("option", "maxDate", self.endDate());
		//	jQuery(".datepicker").datepicker("option", "minDate", self.startDate());

		jQuery(".datepicker_ayp_start").datepicker("option", "maxDate", academicYearEndDate);
		jQuery(".datepicker_ayp_end").datepicker("option", "maxDate", academicYearEndDate);

		jQuery(".datepicker_ayp").datepicker("option", "minDate", academicYearStartDate);
		jQuery(".datepicker_ayp").datepicker("option", "maxDate", academicYearEndDate);

		//set previous date here
		self.endDate.previousDate = self.endDate();

	});
	var dateSourceType = "";
	self.eventData = ko.observableArray([]);
	self.checkForValidity = function(dateSourceType) {

		//return;
		var message = "";
		ko.utils.arrayForEach(self.eventData(), function(item) {
			var itemEvent = item;

			if (ko.isObservable(itemEvent.startDate)) {
				console.log("observable item", itemEvent)
				var strArr1 = itemEvent.startDate().split("/");
				var strArr2 = itemEvent.endDate().split("/");

			} else {
				console.log("Non observable item", itemEvent)
				var strArr1 = itemEvent.startDate.split("/");
				var strArr2 = itemEvent.endDate.split("/");
			}
			var ayp_strArr1 = self.startDate().split("/");
			var ayp_strArr2 = self.endDate().split("/");
			// years, months, date
			var startDate = new Date(strArr1[2], Number(strArr1[1] - 1), strArr1[0]);
			var endDate = new Date(strArr2[2], Number(strArr2[1] - 1), strArr2[0]);

			var ayp_startDate = new Date(ayp_strArr1[2], Number(ayp_strArr1[1] - 1), ayp_strArr1[0]);
			var ayp_endDate = new Date(ayp_strArr2[2], Number(ayp_strArr2[1] - 1), ayp_strArr2[0]);

			console.log("item Event:", self.startDate(), self.endDate(), startDate, endDate);
			//check for min max of date
			if (dateSourceType == "startDate") {
				if (ayp_startDate > startDate) {
					message = "there is a previous date exist in Events"
				}
			} else {
				if (ayp_endDate < endDate) {
					message = "there is a next date exist in Events"
				}
			}
		});

		ko.utils.arrayForEach(self.holidays(), function(item) {
			var itemEvent = item;
			console.log("item Holiday:", itemEvent.startDate());
			var strArr1 = itemEvent.startDate().split("/");
			var strArr2 = itemEvent.endDate().split("/");
			var ayp_strArr1 = self.startDate().split("/");
			var ayp_strArr2 = self.endDate().split("/");
			// years, months, date
			var startDate = new Date(strArr1[2], Number(strArr1[1] - 1), strArr1[0]);
			var endDate = new Date(strArr2[2], Number(strArr2[1] - 1), strArr2[0]);

			var ayp_startDate = new Date(ayp_strArr1[2], Number(ayp_strArr1[1] - 1), ayp_strArr1[0]);
			var ayp_endDate = new Date(ayp_strArr2[2], Number(ayp_strArr2[1] - 1), ayp_strArr2[0]);

			console.log("holiday-------->", self.startDate(), self.endDate(), startDate, endDate);
			//check for min max of date
			if (dateSourceType == "startDate") {
				if (ayp_startDate > startDate) {
					message = "there is a previous date exist in holidays"
				}
			} else {
				if (ayp_endDate < endDate) {
					message = "there is a next date exist in holidays"
				}
			}

		});

		if (message) {

			//alert(message)
			jQuery("#errorText").html(message);
			jQuery("#dialog-alert").dialog("option", "title", "Alert");
			var showAlertDialog = jQuery("#dialog-alert").dialog("open");
			showAlertDialog.dialog("option", "position", "center");

			// Reset the date by dateSourceType
			if (dateSourceType == "startDate") {
				byCode = true;
				self.startDate(self.startDate.previousDate)
				byCode = false;
			}
			if (dateSourceType == "endDate") {
				byCode = true;
				self.endDate(self.endDate.previousDate)
				byCode = false;
			}
			message = ""
		}
	}
	self.setEventData = function(eventResultData) {
		console.log("eventResultData :: ", eventResultData)
		self.eventData(eventResultData)
	}
	self.onDateChange = function(element) {
		console.log("on dateChange", element.name);
		var sdElement;
		var edElement;
		//
		var index = element.name.substr(3);
		var prefix = element.name.substr(0, 3);
		var sdPreFix = "sd_";
		var edPreFix = "ed_";
		//
		if (prefix == edPreFix) {
			//on end date Selected
			console.log("setting in start date");
			edElement = element;
			sdElement = jQuery('input[name="' + sdPreFix+index + '"]')[0];

			var dt1 = jQuery(sdElement).datepicker('getDate');
			var dt2 = jQuery(edElement).datepicker('getDate');

			if (!dt1 && !dt2) {
				dt1 = academicYearStartDate;
				dt2 = academicYearEndDate;
			}
			console.log("dt1:dt2--->", dt1, dt2);
			//jQuery(sdElement).datepicker("option", "minDate", "22-03-2013");
			jQuery(sdElement).datepicker("option", "maxDate", dt2);
			jQuery(edElement).datepicker("option", "minDate", dt1);

			console.log("sdElement :: ", sdElement);
			console.log("edElement :: ", edElement);

		} else if (prefix == sdPreFix) {
			console.log("setting in end date");
			//on start date Selected
			edElement = jQuery('input[name="' + edPreFix+index + '"]')[0];
			sdElement = element

			var dt1 = jQuery(sdElement).datepicker('getDate');
			var dt2 = jQuery(edElement).datepicker('getDate');
			var monthDiff = 0;
			if (dt1) {
				monthDiff = dt1.getMonth() - new Date().getMonth();
				console.log("monthDiff::", monthDiff, dt1, new Date());
			}

			jQuery(edElement).datepicker("option", "minDate", dt1);
			jQuery(edElement).datepicker("option", "defaultDate", monthDiff + 'm');

			if (edElement) {
				console.log("dt1:::dt2--->", dt1, dt2);
				jQuery(sdElement).datepicker("option", "maxDate", dt2);
			}
			console.log("sdElement ::else ", sdElement);
			console.log("edElement ::else ", edElement);

		}

		//jQuery('#dt2').datepicker('option', 'minDate', date2);

	}

	self.removeHoliday = function() {

		console.log("Removing Holiday");

		var removeAlertDialog = jQuery("#dialog-confirm1").dialog("open");
		removeAlertDialog.dialog("option", "position", "center");
		
		ko.dataFor(document.getElementById("dialog-confirm1")).currentItem(this);
		ko.dataFor(document.getElementById("dialog-confirm1")).parentItem(self);
		ko.dataFor(document.getElementById("dialog-confirm1")).type("holiday");
	}

	self.title.subscribe(function(value) {
		console.log("------> title", value);
		var titleVal;
		academicYearPlanTitle = value;

		if (jQuery('#mode').val() == "view") {
			titleVal = "Academic Year: " + value;
		} else if (jQuery('#mode').val() == "create") {
			titleVal = "Create Academic Year: " + value;
		} else {
			titleVal = "Edit Academic Year: " + value;
		}

		jQuery("#aypTitle").text(titleVal);

	});
}
var holiday = function() {
	var self = this;
	self.eventId = ko.observable("");
	self.aypId = ko.observable(aypId);
	self.startDate = ko.observable("").extend({
		required : true
	});
	self.endDate = ko.observable("").extend({
		required : true
	});
	self.title = ko.observable("").extend({
		required : true
	});
	self.desc = ko.observable("");
	self.duration = 1;
	self.eventSectionId = ko.observable("");
	self.isUpdatable = ko.observable(0);
	self.noOfDays = ko.computed(function() {
		//console.log(self.endDate());
		if (self.endDate() === undefined || self.startDate() === undefined || self.endDate() == "" || self.startDate() == "") {
			return 0;
		} else {
			console.log("DATE::::::", self.startDate(), self.endDate());
			var oneDay = 24 * 60 * 60 * 1000;
			// hours*minutes*seconds*milliseconds
			var strArr1 = self.endDate().split("/");
			var strArr2 = self.startDate().split("/");
			var firstDate = new Date(strArr1[2], strArr1[1], strArr1[0]);
			// years, months, date
			var secondDate = new Date(strArr2[2], strArr2[1], strArr2[0]);
			// years, months, date
			var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)) + 1;
			return diffDays;
		}
	})

	self.startDate.subscribe(function(value) {
		if (self.eventId() != "") {
			self.isUpdatable = ko.observable(1);
		}

		/*jQuery(".datepicker_ayp_end").datepicker("destroy");
		 jQuery(".datepicker_ayp_end").datepicker({
		 changeMonth : true,
		 changeYear : true,
		 dateFormat : "dd/mm/yy",
		 minDate : value,
		 maxDate : academicYearEndDate
		 });*/
	});

	self.endDate.subscribe(function(value) {
		if (self.eventId() != "") {
			self.isUpdatable = ko.observable(1);
		}

		/*jQuery(".datepicker_ayp_start").datepicker("destroy");
		 jQuery(".datepicker_ayp_start").datepicker({
		 changeMonth : true,
		 changeYear : true,
		 dateFormat : "dd/mm/yy",
		 minDate : academicYearStartDate,
		 maxDate : value
		 });*/
	});

	self.holidayStartDateHandler = function() {
		console.log("datepicker_ayp_start", self.startDate(), self.endDate());

		//	jQuery( ".datepicker_ayp_start" ).datepicker( "option", "maxDate", self.endDate() );
		//jQuery( ".datepicker_ayp_start" ).datepicker( "show" );
		//jQuery( ".datepicker_ayp_start" ).datepicker( "refresh" );
		/*	jQuery(".datepicker_ayp_start").datepicker("destroy");
		 jQuery(".datepicker_ayp_start").datepicker({
		 changeMonth : true,
		 changeYear : true,
		 dateFormat : "dd/mm/yy",
		 minDate : academicYearStartDate,
		 maxDate : self.endDate()
		 });
		 */
	}

	self.holidayEndDateHandler = function() {
		console.log("datepicker_ayp_end", self.startDate());
		//	jQuery( ".datepicker_ayp_end" ).datepicker( "option", "minDate", self.startDate() );
		//jQuery( ".datepicker_ayp_end" ).datepicker( "show" );
		/*	jQuery(".datepicker_ayp_end").datepicker("destroy");
		 jQuery(".datepicker_ayp_end").datepicker({
		 changeMonth : true,
		 changeYear : true,
		 dateFormat : "dd/mm/yy",
		 minDate : self.startDate(),
		 maxDate : academicYearEndDate
		 });*/

	}
};

this.calculateDays = function() {

	return "5";
}
function genaralInfoTabChangeHandler(event) {

	console.log("tab changes");
	isHolidaySelectable = true;
	isEventSelectable = false;
	//	ko.applyBindings(new createAcademicYearModel());
}

function sectionsTabChangeHandler(event) {
	console.log("tab changes");

	if (aypId == "") {

		jQuery("#errorText").html("To proceed, save the current tab: <b>General Info.</b>");
		jQuery("#dialog-alert").dialog("option", "title", "Alert");
		var alertDialog = jQuery("#dialog-alert").dialog("open");
		alertDialog.dialog("option", "position", "center");
		return;
	}

	//	jQuery( "#tabs" ).tabs( "option", "active", 0 );
	//	  jQuery("#tabs").click('#tabs-3')
	//  e.preventDefault();
	if (!isSectionsLoaded) {
		console.log("editEventHolidayOnly", editEventHolidayOnly());
		showLoader(true, TYPE_LOADING);
		getSchoolAcademicSections("");
	}

}

function eventsTabChangeHandler(event) {
	console.log("tab changes");

	if (aypId == "") {
		//alert("Please Create Academic Year Plan");
		jQuery("#errorText").html("To proceed, save the current tab: <b>General Info.</b>");
		jQuery("#dialog-alert").dialog("option", "title", "Alert");
		alertDialog = jQuery("#dialog-alert").dialog("open");
		alertDialog.dialog("option", "position", "center");
		return;
	}

	if (!isEventsLoaded) {
		showLoader(true, TYPE_LOADING);
		getSchoolAcademicEvents();
	}

	isHolidaySelectable = false;
	isEventSelectable = true;

}

function showHelp() {
	console.log("-------> showing help dialog");

	if (!isHelpActive) {
		isHelpActive = true;
		helpType = "ayp";
		var active = jQuery("#tabs").tabs("option", "active");
		help_scrollPosition = 'ayp_section_' + active;

		jQuery(".help").load("/ce-static-testedge/common/html/help.html", function() {
			//scrollTo('ayp_section_'+active);
			console.log('ayp_section_' + active);
		});

	} else {
		isHelpActive = false;
		jQuery(".help").empty();
	}
}

function closeHelpSection() {
	console.log("closing help section");
	isHelpActive = false;
	jQuery(".help").empty();
}

function retrunToAcademicYear(event) {
	console.log("returning to Academic Year");
	location.href = url.replace("p_p_state=exclusive", "p_p_state=normal") + "getAcademics";
}

this.saveAcademicYearPlan = function() {

	var vm = ko.validation.group(this);
	//	var vm1 = ko.validation.group(this.holidays()[0]);

	if (this.isValid() == false) {
		console.log("thanQ");
		vm.showAllMessages();
		//	alert("Please fill all Required fields before saving.");

		jQuery("#errorText").html("Error! Some of the required field are not correctly entered. Close this message to view the exact nature of the error.");
		jQuery("#dialog-alert").dialog("option", "title", "Error");
		var alertErrorDialog = jQuery("#dialog-alert").dialog("open");
		alertErrorDialog.dialog("option", "position", "center");
		return;
	}

	for (var i = 0; i < this.holidays().length; i++) {
		var vm1 = ko.validation.group(this.holidays()[i]);

		if (vm1().length != 0) {
			vm1.showAllMessages();
			//alert("Please fill all Required fields before saving.");
			jQuery("#errorText").html("Error! Some of the required field are not correctly entered. Close this message to view the exact nature of the error.");
			jQuery("#dialog-alert").dialog("option", "title", "Error");
			var alertErrorDialog = jQuery("#dialog-alert").dialog("open");
			alertErrorDialog.dialog("option", "position", "center");
			return;
		}
	}

	showLoader(true, TYPE_SAVING);
	var self = this;
	var mapping = {
		'ignore' : ["noOfDays", "errors", "eventData"]
	}
	var jsonData = ko.mapping.toJSON(this, mapping)
	console.log(jsonData);
	jQuery.ajax({
		data : {
			savedata : jsonData
		},
		url : url + "saveSchoolAcademic",
		type : "post",
		success : function(result) {

			jQuery("#tabs").tabs("option", "disabled", [])// Enabling other tabs ofter aypId is created
			console.log(result);
			/** Will bind after aypId is Updated---START **/
			/*	ko.applyBindings(new sectionsViewModel(),document.getElementById('tabs-2'));
			 ko.applyBindings(new createSectionViewModel(),document.getElementById('create-Section'));
			 ko.applyBindings(new eventsModel(),document.getElementById('tabs-3'));
			 ko.applyBindings(new addEventViewModel(),document.getElementById('add-Event'));	*/
			if (aypId == "") {
				aypId = result.aypId;
				myEventsModel = new eventsModel();
				ko.applyBindings(new sectionsViewModel(), document.getElementById('tabs-2'));
				ko.applyBindings(new createSectionViewModel(""), document.getElementById('create-Section'));
				ko.applyBindings(myEventsModel, document.getElementById('tabs-3'));
				ko.applyBindings(new addEventViewModel(), document.getElementById('add-Event'));

				/* Will be added for single time*/
				sectionCategories = new Array();
				var obj = new Object();
				obj.sectionId = "";
				obj.sectionTitle = "School";
				sectionCategories.push(obj);
				ko.dataFor(document.getElementById("add-Event")).availableCategories(sectionCategories);

				//	ko.applyBindings(new deleteConfirmViewModel(), document.getElementById('dialog-confirm1'));

				getWorkingDays();
			}
			/** Will bind after aypId is Updated---END **/

			self.aypId(aypId);
			/*	self.holidays.removeAll();
			for (var i = 0; i < result.holidays.length; i++) {
			var holidayView = new holiday();
			var obj = result.holidays[i];
			console.log("holiday view", holidayView);

			holidayView.title(obj.title);
			holidayView.startDate(obj.startDate);
			holidayView.endDate(obj.endDate);
			holidayView.eventId(obj.eventId);
			holidayView.eventSectionId("");
			//holidayView.eventType(0);
			holidayView.isUpdatable(0);
			//holidayView.duration(1);

			self.holidays.push(holidayView);
			}
			*/
			/*	for (var i = 0; i < self.holidays().length; i++) {
			console.log("EventId--->", result.holidays[i].eventId);
			self.holidays()[i].aypId(aypId);
			self.holidays()[i].eventId(result.holidays[i].eventId);
			self.holidays()[i].isUpdatable(0);
			}
			*/
			//	console.log("aypId:" + aypId);
			//	console.log("------>", JSON.stringify(result));

			//self = ko.mapping.fromJS(result);
			console.log("self--------->", self);

			console.log("---------> Sorting");
			/*	self.holidays.sort(function(item1, item2) {
			 console.log(item1.startDate(), item2.startDate());
			 var firstDate;
			 var lastDate;
			 var item1Arr = item1.startDate().split("/");
			 var item2Arr = item2.startDate().split("/");

			 firstDate = new Date(item1Arr[2], item1Arr[1], item1Arr[0]);
			 lastDate = new Date(item2Arr[2], item2Arr[1], item2Arr[0]);

			 if (firstDate > lastDate) {
			 return 1;
			 } else if (firstDate < lastDate) {
			 return -1;
			 } else {
			 return 0;
			 }

			 });*/

			showLoader(false, TYPE_SAVING, showConfirmation);
			getWorkingDays();
			updateAllDates();

		},
		error : function(jqXHR, textStatus, errorThrown) {
			console.log("error saveAcademicYearPlan");
			showLoader(false);

			jQuery("#errorText").html("Error! occured while performing Server Operation");
			jQuery("#dialog-alert").dialog("option", "title", "Error");
			var alertErrorDialog = jQuery("#dialog-alert").dialog("open");
			alertErrorDialog.dialog("option", "position", "center");
		}
	});
}

this.returnBack = function() {
	console.log("returning back");
	location.href = url.replace("p_p_state=exclusive", "p_p_state=normal") + "getAcademics";
}

this.addHoliday = function() {
	console.log("Adding New Holiday");
	jQuery('#ayp_wrap').scrollTop(jQuery('#ayp_wrap').height);
	//document.getElementById( 'btn-addHoliday' ).scrollIntoView();
	this.holidays.push(new holiday());

	//	window.location.hash = ".eventWrap";
}
function scrollTo(hash) {
	console.log("------> scroll to");
	var yScroll = document.body.scrollTop;
	//	window.location.hash = id;
	window.location.hash = "#" + hash;
	document.body.scrollTop = yScroll;
}

this.saveHolidays = function() {
	console.log("Save Holidays", this);
	var self = this;
	var mapping = {
		'ignore' : ["noOfDays"]//,"title", "aypId","startDate", "endDate"]
	}
	var jsonData = ko.mapping.toJSON(this.holidays, mapping)
	console.log(jsonData);

	jQuery.ajax({
		data : {
			savedata : jsonData
		},
		url : url + "saveSchoolEvent",
		type : "post",
		success : function(result) {
			console.log("------> Result", result);
			console.log(self);

			for (var i = 0; i < self.holidays().length; i++) {
				console.log(result[i].eventId);
				self.holidays()[i].eventId = result[i].eventId
			}
		},
		error : function(jqXHR, textStatus, errorThrown) {
			console.log("error saveHolidays");
		}
	});
}
/* STARTING FOR EVENTS */

var eventVM = function(_aypId, _eventId, _title, _startDate, _endDate, _category, _desc, _durationVal, _eventSectionId) {
	console.log("_eventSectionId:", _eventSectionId);
	console.log("_category:", _category);

	var self = this;
	//self.aypId = ko.observable("acad-60bf7bdf-6ef2-456e-a981-e00be80ba260");
	self.aypId = ko.observable(aypId);
	self.eventId = ko.observable(_eventId);
	self.title = ko.observable(_title);
	self.startDate = ko.observable(_startDate);
	self.endDate = ko.observable(_endDate);
	self.durationVal = ko.observable(_durationVal);
	self.category = ko.observable(_category);
	self.desc = ko.observable(_desc);
	self.isEditing = ko.observable("false");
	self.eventSectionId = ko.observable(_eventSectionId);
	self.dateDuration = ko.computed(function() {
		return self.startDate() + " to " + self.endDate();
	});
	self.eventName = ko.computed(function() {
		console.log("self.category()::", self.category());
		if (self.category()) {
			console.log("---> Inside category");
			return self.category().sectionTitle + " Event";
		}
	});
	self.noOfDays = ko.computed(function() {
		if (self.endDate() === undefined || self.startDate() === undefined || self.endDate() == "" || self.startDate() == "") {
			return 0;
		} else {
			var diffDays = 0;
			var oneDay = 24 * 60 * 60 * 1000;
			// hours*minutes*seconds*milliseconds
			var strArr1 = self.endDate().split("/");
			var strArr2 = self.startDate().split("/");
			var firstDate = new Date(strArr1[2], strArr1[1], strArr1[0]);
			// years, months, date
			var secondDate = new Date(strArr2[2], strArr2[1], strArr2[0]);
			// years, months, date
			var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)) + 1;
			return diffDays + " days";
		}
	});
	self.isEditing.subscribe(function(newValue) {
		if (self.isEditing() == "true") {
			console.log("->", self);
			//console.log("->",this);
			postbox.notifySubscribers(self, "editEvent");

		}
	});
	console.log("-----------END of Add EVENT");
}
var eventsModel = function() {

	var self = this;
	self.events = ko.observableArray();
	postbox.subscribe(function(newValue) {
		console.log("-------->", this.events().length, newValue.title());

		var hasPrasent = false;
		for (var i = 0; i < this.events().length; i++) {
			console.log(i);
			console.log(this.events());
			console.log(this.events()[i].eventId());
			if (this.events()[i].eventId() == newValue.eventId()) {
				hasPrasent = true;
				break;
			}
		}

		if (hasPrasent) {
			this.events()[i].title(newValue.title());
			this.events()[i].startDate(newValue.startDate());
			this.events()[i].endDate(newValue.endDate());
			this.events()[i].category(newValue.category());
			this.events()[i].desc(newValue.desc());
			this.events()[i].durationVal(newValue.durationVal());
			this.events()[i].eventSectionId(newValue.eventSectionId());
		} else {
			var eventJSData = ko.mapping.toJS(newValue);
			console.log("--------> Adding event details", newValue, eventJSData);
			this.events.push(new eventVM(eventJSData.aypId, eventJSData.eventId, eventJSData.title, eventJSData.startDate, eventJSData.endDate, eventJSData.category, eventJSData.desc, eventJSData.durationVal, eventJSData.eventSectionId));
		}

		//	ko.cleanNode.document.getElementById("add-Event");
		//	ko.applyBindings(new addEventViewModel(),document.getElementById("add-Event"));
		console.log("this.events().length:", this.events().length);

		myAcademicYearModel.setEventData(this.events())
		newValue.eventId("");
		newValue.title("");
		newValue.startDate("");
		newValue.endDate("");
		newValue.desc("");
		newValue.durationVal("All Day");
		newValue.category(null);
		newValue.isChanged("false");

		//updateAllDates();
		//newValue.eventSectionId("");
		//newValue = new addEventViewModel();

		var vm = ko.validation.group(newValue);
		vm.showAllMessages(false);
		console.log(newValue);

		console.log("---------> Sorting Events");
		self.events.sort(function(item1, item2) {
			console.log(item1.startDate(), item2.startDate());
			var firstDate;
			var lastDate;
			var item1Arr = item1.startDate().split("/");
			var item2Arr = item2.startDate().split("/");

			firstDate = new Date(item1Arr[2], Number(item1Arr[1] - 1), item1Arr[0]);
			lastDate = new Date(item2Arr[2], Number(item2Arr[1] - 1), item2Arr[0]);

			if (firstDate > lastDate) {
				return 1;
			} else if (firstDate < lastDate) {
				return -1;
			} else {
				return 0;
			}

		});

	}, this, "addEvents");

	deleteEvent = function(_event) {
		console.log("Deleting Event");
		var deleteDialog = jQuery("#dialog-confirm1").dialog("open");
		deleteDialog.dialog("option", "position", "center");
		
		ko.dataFor(document.getElementById("dialog-confirm1")).currentItem(this);
		ko.dataFor(document.getElementById("dialog-confirm1")).parentItem(self);
		ko.dataFor(document.getElementById("dialog-confirm1")).type("event");

	}
}

this.editEvent = function(_event) {
	console.log("Editing Event", _event.title());
	console.log(_event);
	
	var editEventDialog = jQuery("#add-Event").dialog("open");
	editEventDialog.dialog("option", "position", "center");
		
	this.isEditing("true");
}

this.saveEventsHandler = function() {

	console.log("saving events");
}
var addEventViewModel = function() {
	var self = this;
	//self.aypId = ko.observable("acad-60bf7bdf-6ef2-456e-a981-e00be80ba260");
	self.aypId = ko.observable(aypId);
	self.eventId = ko.observable("");
	self.title = ko.observable("").extend({
		required : true
	});
	self.startDate = ko.observable("").extend({
		required : true
	});
	self.endDate = ko.observable("").extend({
		required : true
	});
	self.durationVal = ko.observable("");
	self.category = ko.observable("").extend({
		required : true
	});
	;
	self.desc = ko.observable("").extend({
		required : true
	});
	self.isUpdatable = ko.observable(0);
	self.isChanged = ko.observable("false");
	self.duration = ko.computed(function() {
		return self.durationVal() == "All Day" ? 1 : 0;
	});
	self.eventType = ko.computed(function() {
		if (self.category() != "" && self.category() != undefined) {
			console.log("::::", self.category().sectionId);
			return self.category().sectionTitle == "School" ? 1 : 2;
		}
	})
	self.eventSectionId = ko.computed(function() {

		if (self.category() != "" && self.category() != undefined) {
			console.log("::::", self.category().sectionId);
			return self.category().sectionId;
		} else {
			return "";
		}
	})
	//	self.availableCategories = ko.observableArray([{sectionId:"1",sectionTitle:"School"},{sectionId:"2",sectionTitle:"Per-Primary"},{sectionId:"3",sectionTitle:"Primary"},{sectionId:"4",sectionTitle:"Secondary"},{sectionId:"5",sectionTitle:"Higher Secondary"}])
	self.availableCategories = ko.observableArray(sectionCategories)
	self.durationOptions = ko.observableArray(["All Day", "Half Day"])
	self.isChanged.subscribe(function(newValue) {
		if (self.isChanged() == "true") {
			console.log("->", self);
			//console.log("->",this);
		//	postbox.notifySubscribers(self, "addEvents"); // Commented for Initial Error with Add Event
		}
	});

	postbox.subscribe(function(newValue) {
		console.log("editing Event", newValue);

		self.title(newValue.title());
		self.eventId(newValue.eventId());
		self.startDate(newValue.startDate());
		self.endDate(newValue.endDate());
		self.durationVal(newValue.durationVal());
		self.category(newValue.category());
		self.desc(newValue.desc());

		newValue.isEditing("false");
	}, this, "editEvent");

	self.startDate.subscribe(function(value) {
		if (self.eventId() != "") {
			self.isUpdatable = ko.observable(1);
		}
		if (!value) {
			value = academicYearStartDate;
		}

		var dateArr = value.split("/");

		jQuery("#eventEndDate").datepicker("option", "minDate", value);
		monthDiff = dateArr[1] - new Date().getMonth() - 1;
		console.log("monthDiff::", monthDiff, self.startDate(), new Date());
		jQuery("#eventEndDate").datepicker("option", "defaultDate", monthDiff + 'm');
	});

	self.endDate.subscribe(function(value) {
		if (self.eventId() != "") {
			self.isUpdatable = ko.observable(1);
		}
		if (!value) {
			value = academicYearEndDate;
		}
		jQuery("#eventStartDate").datepicker("option", "maxDate", value);
	});

	/*	self.dateDuration = ko.computed(function(){

	 return self.startDate() + " to " +self.endDate();
	 });
	 self.noOfDays = ko.computed(function(){
	 if(self.endDate() === undefined || self.startDate() === undefined ||self.endDate() == "" || self.startDate() == "")
	 {
	 return 0;
	 }
	 else
	 {
	 var diffDays = 0;
	 var oneDay = 24*60*60*1000;	// hours*minutes*seconds*milliseconds
	 var strArr1 = self.endDate().split("/");
	 var strArr2 = self.startDate().split("/");
	 var firstDate = new Date(strArr1[2],strArr1[1],strArr1[0]); // years, months, date
	 var secondDate = new Date(strArr2[2],strArr2[1],strArr2[0]);// years, months, date
	 var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));
	 return diffDays + " days";
	 }
	 });
	 self.eventName = ko.computed(function(){
	 return self.category() + " Event";
	 });	*/
}

this.openAddEventWindow = function() {
	console.log("--------> Open Add event window");
}

this.addEvent = function(data) {
	console.log("--> adding event");
	var vm = ko.validation.group(this);
	//	var vm1 = ko.validation.group(this.holidays()[0]);

	if (this.isValid() == false) {
		console.log("thanQ");
		vm.showAllMessages();
		//alert("Please fill all Required fields before saving.");

		//jQuery("#dialog-validationError-alert").dialog("open");
		jQuery("#errorText").html("Error! Some of the required field are not correctly entered. Close this message to view the exact nature of the error.");
		jQuery("#dialog-alert").dialog("option", "title", "Error");
		var alertErrorDialog = jQuery("#dialog-alert").dialog("open");
		alertErrorDialog.dialog("option", "position", "center");
		return;
	} else {
		showLoader(true, TYPE_SAVING);
	}

	var mapping = {
		'ignore' : ["noOfDays", "eventName", "dateDuration", "availableCategories", "isChanged", "durationOptions", "category", "durationVal", "errors"]
	}
	var self = this;
	// Collecting addEventViewModel
	var jsonData = ko.mapping.toJSON(this, mapping)
	jsonData = "[" + jsonData.toString() + "]";
	console.log(jsonData);
	jQuery.ajax({
		data : {
			savedata : jsonData
		},
		url : url + "saveSchoolEvent",
		type : "post",
		success : function(result) {
			console.log("------> Result", result);
			console.log(result[0].eventId);

			jQuery("#add-Event").dialog("close");
			// Updating eventId to addEventViewModel
			self.eventId(result[0].eventId);
			// to Invoke addition of Event to Events Model
			//	self.isChanged("true");
			
			var hasPrasent = false;
			for (var i = 0; i < myEventsModel.events().length; i++) {
				console.log(i);
				console.log(myEventsModel.events());
				console.log(myEventsModel.events()[i].eventId());
				if (myEventsModel.events()[i].eventId() == self.eventId()) {
					hasPrasent = true;
					break;
				}
			}

			if (hasPrasent) {
				myEventsModel.events()[i].title(self.title());
				myEventsModel.events()[i].startDate(self.startDate());
				myEventsModel.events()[i].endDate(self.endDate());
				myEventsModel.events()[i].category(self.category());
				myEventsModel.events()[i].desc(self.desc());
				myEventsModel.events()[i].durationVal(self.durationVal());
				myEventsModel.events()[i].eventSectionId(self.eventSectionId());
			} else {
				var eventJSData = ko.mapping.toJS(self);
				console.log("--------> Adding event details", self, eventJSData);
				myEventsModel.events.push(new eventVM(eventJSData.aypId, eventJSData.eventId, eventJSData.title, eventJSData.startDate, eventJSData.endDate, self.category(), eventJSData.desc, eventJSData.durationVal, eventJSData.eventSectionId));
			}

			myAcademicYearModel.setEventData(myEventsModel.events())
			self.eventId("");
			self.title("");
			self.startDate("");
			self.endDate("");
			self.desc("");
			self.durationVal("All Day");
			self.category(null);
			self.isChanged("false");

			var vm = ko.validation.group(self);
			vm.showAllMessages(false);
			console.log(self);

			console.log("---------> Sorting Events");
			myEventsModel.events.sort(function(item1, item2) {
				console.log(item1.startDate(), item2.startDate());
				var firstDate;
				var lastDate;
				var item1Arr = item1.startDate().split("/");
				var item2Arr = item2.startDate().split("/");

				firstDate = new Date(item1Arr[2], Number(item1Arr[1] - 1), item1Arr[0]);
				lastDate = new Date(item2Arr[2], Number(item2Arr[1] - 1), item2Arr[0]);

				if (firstDate > lastDate) {
					return 1;
				} else if (firstDate < lastDate) {
					return -1;
				} else {
					return 0;
				}

			});
			showLoader(false);
			getWorkingDays();
			updateAllDates();
		},
		error : function(jqXHR, textStatus, errorThrown) {
			console.log("error addEvent");

			showLoader(false);
			//jQuery("#dialog-error-alert").dialog("open");
			jQuery("#errorText").html("Error! occured while performing Server Operation");
			jQuery("#dialog-alert").dialog("option", "title", "Error");
			var alertErrorDialog = jQuery("#dialog-alert").dialog("open");
			alertErrorDialog.dialog("option", "position", "center");
		}
	});
}

this.cancelEvent = function() {
	console.log("------> Cancel Event");

	var vm = ko.validation.group(this);
	vm.showAllMessages(false);

	var self = this;

	self.eventId("");
	self.title("");
	self.startDate("");
	self.endDate("");
	self.desc("");
	self.durationVal("All Day");
	self.category(null);
}

this.invokeAddEventHandler = function() {
	console.log("--------qw----->", ko.dataFor(document.getElementById("add-Event")));
	//ko.dataFor(document.getElementById("add-Event")).title("Yurekha");
	//ko.cleanNode(jQuery("#add-Event"));
	//ko.applyBindings(new addEventViewModel(),document.getElementById('add-Event'));

	var vm = ko.validation.group(ko.dataFor(document.getElementById("add-Event")));
	vm.showAllMessages(false);
	/*jQuery(".datepicker").datepicker("destroy");
	 jQuery(".datepicker").datepicker({
	 changeMonth : true,
	 changeYear : true,
	 dateFormat : "dd/mm/yy",
	 minDate : "-1Y",
	 maxDate : "+1Y"
	 });
	 */
}
function showConfirmation() {
	console.log("-------->showConfirmation");
	//jQuery("#dialog-confirm-save").dialog("open");

	jQuery("#errorText").html("Changes made are saved successfully.");
	jQuery("#dialog-alert").dialog("option", "title", "Confirmation");
	var showConformDialog = jQuery("#dialog-alert").dialog("open");
	showConformDialog.dialog("option", "position", "center");

}

jQuery(function() {

	console.log("--------> DOM loaded");

	if (jQuery('#baseUrl').val()) {
		url = jQuery('#baseUrl').val().replace("DUMMY", "");
		aypId = jQuery('#aypId').val();
		console.log("baseUrl:", url);
	} else {
		aypId = "acad-29248e35-97fc-4c0b-98a0-c7f806825633";
		url = "http://mvms121:8080/group/testessc-mud/academic-year?p_p_id=AYPManagement_WAR_ceportaltestedge&p_p_lifecycle=0&p_p_state=exclusive&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_AYPManagement_WAR_ceportaltestedge_Operation="

	}

	/* Settings for Date Controller Start */
	displayAttendance = false;
	displayPendingAttendance = false;
	isHolidaySelectable = true;
	displayDailyLog = false;
	displayNonWorkingDays = false;
	/* Settings for Date Controller END  */
	editMode = jQuery('#mode').val() == 'view' ? false : true;
	console.log("url:", url);
	console.log("aypId:", aypId);
	console.log("editMode:", editMode);

	if (aypId != "") {
		getWorkingDays();
	}

	/*	jQuery(".datepicker_ayp_start").datepicker({
	changeMonth : true,
	changeYear : true,
	dateFormat : "dd/mm/yy",
	minDate : "-0Y",
	maxDate : "+2Y"
	});

	jQuery(".datepicker_ayp_end").datepicker({
	changeMonth : true,
	changeYear : true,
	dateFormat : "dd/mm/yy",
	minDate : "-0Y",
	maxDate : "+2Y"
	});
	*/
	/*	ko.applyBindings(new sectionsViewModel(), document.getElementById('tabs-2'));
	ko.applyBindings(new createSectionViewModel(""), document.getElementById('create-Section'));
	ko.applyBindings(new eventsModel(), document.getElementById('tabs-3'));
	ko.applyBindings(new addEventViewModel(), document.getElementById('add-Event'));
	ko.applyBindings(new deleteConfirmViewModel(), document.getElementById('dialog-confirm1'));
	*///	ko.applyBindings(new sectionsViewModel());

})
//alert("applying binding ");

